/** 车辆保险管理 */

import React, {useEffect, useState} from 'react'
import {Button, Space, message} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history, connect, useModel} from 'umi'
import {ArrowUpOutlined, ArrowDownOutlined} from '@ant-design/icons'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import Permissions from '@/components/Permissions'
import {getHolderDictInfo} from '@/service/common'
import CustomTable from '@/components/Table'
import {getDict} from '@/service/common/dict'
import {
	getAssertsCarInsurancebaseList,
	getInsurancePage,
	getStartOverPage,
	getSuspensionPage,
	importStartOverInsurance,
	importSuspensionInsurance,
	insuranceImport,
	uploadInsurancePhoto,
} from '@/service/carMessage/insurance'
import {modalApi} from '@/utils/modalReq'
import BatchUpload from '@/components/BatchUpload'
import {getXZCarTypeList} from '@/service/carMessage/list'
import ImageImport from './components/ImageImport'
import {uploadFileUrl} from '@/service/common/upload'
import {downloadDocumentUrl} from '@/service/common/download'
import {modelSeriesFun} from '@/utils/common'

interface DataType {
	carrierEndTime: string
	carrierStartTime: string
	commercialStartTime: string
	commercialEndTime: string
	compulsoryEndTime: string
	compulsoryStartTime: string
	carId: number
	id: string
	carPlateNo: string
	carBrandSeries: string
	serviceType: string
	contacts: string
	status: string
	date: string
}

const formItemLayout = {
	labelCol: {flex: '120px'},
	wrapperCol: {flex: '1'},
}

const archives = () => {
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [dataSourse, setDataSourse] = useState<any[]>([])
	const [dictData, setDictData] = useState<any>()
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState()
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [isCarImgModalOpen, setIsCarImgModalOpen] = useState(false)
	const [carTypeList, setCarTypeList] = useState<any>([])
	const [importType, setImportType] = useState<string>('')
	const [batchUploadData, setBatchUploadData] = useState<any>({})
	const [searchData, setSearchData] = useState({})
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	// 持有方数据
	const [holderDict, setHolderDict] = useState([])
	/** 获取持有方数据 */
	const getHolderDictInfoFun = () => {
		getHolderDictInfo({type: 'holder'}).then((res: any) => {
			if (res?.success) {
				setHolderDict(res?.data)
			}
		})
	}

	// 获取品牌车系
	const onCarTypeListFun = () => {
		getXZCarTypeList().then((res: any) => {
			if (res?.success) {
				setCarTypeList(modelSeriesFun(res.data))
			}
		})
	}

	// 获取车辆保险列表
	const getData = () => {
		setLoading(true)
		getAssertsCarInsurancebaseList({...params, ...searchData})
			.then((res: any) => {
				if (res?.success) {
					setDataSourse(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				}
			})
			.catch((err) => {
				setDataSourse([])
				message.error(err)
				setLoading(false)
			})
	}

	useEffect(() => {
		getData()
	}, [params])

	useEffect(() => {
		getHolderDictInfoFun()
		onCarTypeListFun()
		getDict(
			{
				dictKeys: [
					'commercial_company_code',
					'carrier_company_code',
					'compulsory_company_code',
				],
			},
			(res: any) => {
				setDictData(res)
			},
		)
	}, [])

	/** 点击详情及编辑事件 */
	const onDetails = (type: string, record: DataType) => {
		history.push({
			pathname: `/carMessage/insurance/${type}`,
			query: {
				id: record?.id,
			},
		})
	}
	/** 保险状态 */
	const getInsuranceType = (text: string | number) => {
		if (text === 1) {
			return '正常'
		}
		if (text === 2) {
			return '停保'
		}
		if (text === 2) {
			return '已过期'
		}
		return '-'
	}

	/** 停延保状态 */
	const getOutOfWarranty = (text: string | number) => {
		if (text === 1) {
			return '正常'
		}
		if (text === 2) {
			return '停保中'
		}
		if (text === 3) {
			return '延保中'
		}
		return '-'
	}

	const columns: ColumnsType<DataType> = [
		{
			title: '车辆ID',
			dataIndex: 'carId',
			align: 'center',
			width: 100,
		},
		{
			title: '车牌号',
			dataIndex: 'carPlateNo',
			align: 'center',
			width: 100,
		},
		{
			title: '品牌车型车系',
			dataIndex: 'carBrandSeries',
			align: 'center',
			width: 130,
		},
		{
			title: '持有方',
			dataIndex: 'holderName',
			align: 'center',
			width: 100,
		},
		{
			title: '所属公司',
			dataIndex: 'companyName',
			align: 'center',
			width: 160,
		},
		{
			title: '所有人',
			dataIndex: 'ownerName',
			align: 'center',
			width: 100,
		},
		{
			title: '城市',
			dataIndex: 'cityName',
			align: 'center',
			width: 100,
		},
		{
			title: '运营分类',
			dataIndex: 'operationType',
			align: 'center',
			width: 100,
			render: (text) => {
				if (text === 1) {
					return '运营'
				}
				if (text === 2) {
					return '代运营'
				}
				return '-'
			},
		},
		{
			title: '资产所有方',
			dataIndex: 'assertsOwnerName',
			align: 'center',
			width: 120,
		},
		{
			title: '交强险状态',
			dataIndex: 'compulsoryStatus',
			align: 'center',
			width: 120,
			render: (text) => getInsuranceType(text),
		},
		{
			title: '交强险被保人',
			dataIndex: 'compulsoryInsured',
			align: 'center',
			width: 160,
		},
		{
			title: '交强险公司',
			dataIndex: 'compulsoryCompanyName',
			align: 'center',
			width: 120,
		},
		{
			title: '交强险保单号',
			dataIndex: 'compulsoryNo',
			align: 'center',
			width: 130,
		},
		{
			title: '交强险保费',
			dataIndex: 'compulsoryTotalFee',
			align: 'center',
			width: 120,
		},
		{
			title: '交强险日期',
			dataIndex: 'jqxrq',
			align: 'center',
			width: 150,
			render: (_, record) => (
				<>
					<div>始：{record?.compulsoryStartTime}</div>
					<div>止：{record?.compulsoryEndTime}</div>
				</>
			),
		},
		{
			title: '商业险状态',
			dataIndex: 'commercialStatus',
			align: 'center',
			width: 120,
			render: (text) => getInsuranceType(text),
		},
		{
			title: '商业险被保人',
			dataIndex: 'commercialInsured',
			align: 'center',
			width: 160,
		},
		{
			title: '商业险公司',
			dataIndex: 'commercialCompanyName',
			align: 'center',
			width: 120,
		},
		{
			title: '商业险保单号',
			dataIndex: 'commercialNo',
			align: 'center',
			width: 130,
		},
		{
			title: '商业险保费',
			dataIndex: 'commercialTotalFee',
			align: 'center',
			width: 120,
		},
		{
			title: '商业险日期',
			dataIndex: 'syxrq',
			align: 'center',
			width: 150,
			render: (_, record) => (
				<>
					<div>始：{record?.commercialStartTime}</div>
					<div>止：{record?.commercialEndTime}</div>
				</>
			),
		},
		{
			title: '承责险状态',
			dataIndex: 'carrierStatus',
			align: 'center',
			width: 120,
			render: (text) => getInsuranceType(text),
		},
		{
			title: '承责险被保人',
			dataIndex: 'carrierInsured',
			align: 'center',
			width: 160,
		},
		{
			title: '承责险公司',
			dataIndex: 'carrierCompanyName',
			align: 'center',
			width: 120,
		},
		{
			title: '承责险单号',
			dataIndex: 'carrierNo',
			align: 'center',
			width: 120,
		},
		{
			title: '承责险保额',
			dataIndex: 'carrierTotalFee',
			align: 'center',
			width: 120,
		},
		{
			title: '整车保费',
			dataIndex: 'carrierVehiclePremium',
			align: 'center',
			width: 120,
		},
		{
			title: '承责险日期',
			dataIndex: 'czxrq',
			align: 'center',
			width: 150,
			render: (_, record) => (
				<>
					<div>始：{record?.carrierStartTime}</div>
					<div>止：{record?.carrierEndTime}</div>
				</>
			),
		},
		{
			title: '交强险停延保状态',
			dataIndex: 'compulsoryStopDelayStatus',
			align: 'center',
			width: 120,
			render: (text) => getOutOfWarranty(text),
		},
		{
			title: '商业险停延保状态',
			dataIndex: 'commercialStopDelayStatus',
			align: 'center',
			width: 120,
			render: (text) => getOutOfWarranty(text),
		},
		{
			title: '承责险停延保状态',
			dataIndex: 'carrierStopDelayStatus',
			align: 'center',
			width: 120,
			render: (text) => getOutOfWarranty(text),
		},
		{
			title: '延保日期',
			dataIndex: 'delayDateStr',
			align: 'center',
			width: 250,
		},
		{
			title: '延保天数',
			dataIndex: 'delayDaysStr',
			align: 'center',
			width: 180,
		},
		{
			title: '保险顺延止期',
			dataIndex: 'secondDeadLineStr',
			align: 'center',
			width: 200,
		},
		{
			title: '顺延天数',
			dataIndex: 'continuanceDaysStr',
			align: 'center',
			width: 120,
		},
		{
			title: '延保单号',
			dataIndex: 'delayOrderNoStr',
			align: 'center',
			width: 250,
		},
		{
			title: '延保复始时间',
			dataIndex: 'delayOrderContinuanceStr',
			align: 'center',
			width: 200,
		},
		{
			title: '二次延保日期',
			dataIndex: 'secondDelayDateStr',
			align: 'center',
			width: 250,
		},
		{
			title: '延保天数',
			dataIndex: 'secondDelayDaysStr',
			align: 'center',
			width: 170,
		},
		{
			title: '保险顺延止期',
			dataIndex: 'secondDeadLineStr',
			align: 'center',
			width: 200,
		},
		{
			title: '顺延天数',
			dataIndex: 'secondContinuanceDaysStr',
			align: 'center',
			width: 150,
		},
		{
			title: '二次延保单号',
			dataIndex: 'secondDelayOrderNoStr',
			align: 'center',
			width: 150,
		},
		{
			title: '二次延保复始时间',
			dataIndex: 'secondDelayOrderContinuanceStr',
			align: 'center',
			width: 200,
		},
		{
			title: '停保日期',
			dataIndex: 'stopInsuranceDateStr',
			align: 'center',
			width: 200,
		},
		{
			title: '保险终止日期',
			dataIndex: 'insuranceStopDateStr',
			align: 'center',
			width: 200,
		},
		{
			title: '批改金额',
			dataIndex: 'correctionStr',
			align: 'center',
			width: 200,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 120,
			render: (_, record) => (
				<Space size={12}>
					<Permissions permissionID="amc_assetCenter_carMessage_insurance_view">
						<Button
							type="link"
							onClick={() => {
								onDetails('view', record)
							}}>
							查看
						</Button>
					</Permissions>
					<Permissions permissionID="amc_assetCenter_carMessage_insurance_edit">
						<Button
							type="link"
							onClick={() => {
								onDetails('edit', record)
							}}>
							编辑
						</Button>
					</Permissions>
				</Space>
			),
		},
	]
	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'select',
					label: '持有方',
					name: 'holderId',
					key: 'holderId',
					keys: 'value',
					title: 'valueName',
					items: [...holderDict],
				},
				{
					type: 'input',
					label: '车辆id',
					name: 'carId',
					key: 'carId',
					rules: [
						{
							pattern: /^[0-9]*$/,
							message: '车辆id请输入数字',
						},
					],
				},
				{
					type: 'input',
					label: '车牌号',
					name: 'carPlateNo',
					key: 'carPlateNo',
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'select',
					label: '品牌车型车系',
					name: 'fashionId',
					key: 'fashionId',
					keys: 'id',
					title: 'fullName',
					items: carTypeList,
				},
				{
					type: 'select',
					label: '交强险状态',
					name: 'compulsoryStatus',
					key: 'compulsoryStatus',
					keys: 'value',
					title: 'text',
					items: [
						{value: 1, text: '正常'},
						{value: 2, text: '停保'},
					],
				},
				{
					type: 'select',
					label: '商业险状态',
					name: 'commercialStatus',
					key: 'commercialStatus',
					keys: 'value',
					title: 'text',
					items: [
						{value: 1, text: '正常'},
						{value: 2, text: '停保'},
					],
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'select',
					label: '交强险公司',
					name: 'compulsoryCompanyCode',
					key: 'compulsoryCompanyCode',
					keys: 'dictKey',
					title: 'dictValue',
					items: dictData?.compulsory_company_code,
				},
				{
					type: 'select',
					label: '商业险公司',
					name: 'commercialCompanyCode',
					key: 'commercialCompanyCode',
					keys: 'dictKey',
					title: 'dictValue',
					items: dictData?.commercial_company_code,
				},
				{
					type: 'input',
					label: '商业险保单号',
					name: 'commercialNo',
					key: 'commercialNo',
				},
			],
		},
		{
			type: 'group',
			key: 'group4',
			groupItems: [
				{
					type: 'input',
					label: '交强险保单号',
					name: 'compulsoryNo',
					key: 'compulsoryNo',
				},
				{
					type: 'select',
					label: '承责险状态',
					name: 'carrierStatus',
					key: 'carrierStatus',
					keys: 'value',
					title: 'text',
					items: [
						{value: 1, text: '正常'},
						{value: 2, text: '停保'},
					],
				},
				{
					type: 'select',
					label: '承责险公司',
					name: 'carrierCompanyCode',
					key: 'carrierCompanyCode',
					keys: 'dictKey',
					title: 'dictValue',
					items: dictData?.carrier_company_code,
				},
			],
		},
		{
			type: 'group',
			key: 'group5',
			groupItems: [
				{
					type: 'input',
					label: '承责险保单号',
					name: 'holderId',
					key: 'holderId',
				},
				{
					type: 'select',
					label: '停延保状态',
					name: 'searchStatus',
					key: 'searchStatus',
					keys: 'value',
					title: 'text',
					items: [
						{value: 1, text: '正常'},
						{value: 1, text: '停保中'},
						{value: 1, text: '延保中'},
					],
				},
				{
					type: 'input',
					label: '停保单号',
					name: 'searchSecondDelayNo',
					key: 'searchSecondDelayNo',
				},
			],
		},
		{
			type: 'group',
			key: 'group6',
			groupItems: [
				{
					type: 'input',
					label: '二次停保单号',
					name: 'searchSecondDelayNo',
					key: 'searchSecondDelayNo',
				},
				{},
				{},
			],
		},
	]
	// 搜索
	const onFinish = (values: any) => {
		setSearchData(values)
		setParams({
			current: 1,
			size: 10,
		})
	}
	// 重置
	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '车牌号',
			dataIndex: 'carPlateNo',
			align: 'center',
			width: 120,
		},
		{
			title: '品牌车型车系',
			dataIndex: 'carBrandSeries',
			align: 'center',
			width: 150,
		},
		{
			title: 'VIN码',
			dataIndex: 'vin',
			align: 'center',
			width: 120,
		},
		{
			title: '所属公司',
			dataIndex: 'companyName',
			align: 'center',
			width: 150,
		},
		{
			title: '错误信息',
			dataIndex: 'errorMsg',
			align: 'center',
			width: 200,
			fixed: 'right',
			render: (text: string) => <span>{text || '--'}</span>,
		},
	]
	useEffect(() => {
		let BatchUploadData = {}
		if (importType === '停延保') {
			BatchUploadData = {
				title: '批量停延保',
				importData: importSuspensionInsurance,
				onTableList: getSuspensionPage,
				uploadFileUrl: `${modalApi.carMessage}/assertsCarInsurancebase/importSuspensionInsurance`,
				sourceId: 3,
				templateType: '停延保导入',
			}
		} else if (importType === '复始') {
			BatchUploadData = {
				title: '批量复始',
				importData: importStartOverInsurance,
				onTableList: getStartOverPage,
				uploadFileUrl: `${modalApi.carMessage}/assertsCarInsurancebase/importStartOverInsurance`,
				sourceId: 1,
				templateType: '保险复始导入',
			}
		} else {
			BatchUploadData = {
				title: '批量导入保险',
				importData: insuranceImport,
				onTableList: getInsurancePage,
				uploadFileUrl: `${modalApi.carMessage}/assertsCarInsurancebase/importInsurance`,
				sourceId: 2,
				templateType: '保险导入',
			}
		}

		setBatchUploadData(BatchUploadData)
	}, [importType])

	// 批量导入车辆图片取消
	const carImgModalOpen = () => {
		setIsCarImgModalOpen(() => false)
	}

	const resetList = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}

	// 批量图片上传
	const importImgData = (fileList: any) => {
		const positionReg = [
			{key: 1, label: '交强险'},
			{key: 2, label: '商业险'},
			{key: 3, label: '承运险'},
		]
		const fileLists = fileList.map((item: any) => {
			const arr = item?.response?.data?.filename?.split('.')
			return {
				carPlateNo: arr[0],
				insuranceType: positionReg?.filter(
					(items: {key: number; label: string}) =>
						items.label === arr[1],
				)[0].key,
				mainKey: item?.response?.data?.id,
			}
		})
		uploadInsurancePhoto(fileLists)
			.then((res) => {
				if (res?.success) {
					message.success(res.msg)
					setIsCarImgModalOpen(() => false)
					resetList()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	return (
		<div className={styles.insurance}>
			<div className={styles.content}>
				<div className={styles.search}>
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
					/>
				</div>
				<div className={styles.btnlist}>
					<Space size={12}>
						<Permissions permissionID="amc_assetCenter_carMessage_insurance_batchImport">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => {
									setImportType('导入保险')
									setIsUploadModalOpen(true)
								}}>
								批量导入保险
							</Button>
						</Permissions>
						<Permissions permissionID="amc_assetCenter_carMessage_insurance_batchImportPolicy">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => {
									setIsCarImgModalOpen(() => true)
								}}>
								批量上传保单
							</Button>
						</Permissions>
						<Permissions permissionID="amc_assetCenter_carMessage_insurance_batchStop">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => {
									setImportType('停延保')
									setIsUploadModalOpen(true)
								}}>
								批量停延保
							</Button>
						</Permissions>
						<Permissions permissionID="amc_assetCenter_carMessage_insurance_restatement">
							<Button
								icon={<ArrowUpOutlined />}
								className={styles.warning}
								ghost
								size="small"
								onClick={() => {
									setImportType('复始')
									setIsUploadModalOpen(true)
								}}>
								批量复始
							</Button>
						</Permissions>
					</Space>
					<Space size={12}>
						<Permissions permissionID="amc_assetCenter_carMessage_insurance_batchExprot">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '112',
										queryDesc: '批量导出,resourceId:112',
										queryParam: searchData,
									})
								}}>
								批量导出
							</Button>
						</Permissions>
						<Permissions permissionID="amc_assetCenter_carMessage_insurance_traffic">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '113',
										queryDesc:
											'批量导出交强险,resourceId:113',
										queryParam: searchData,
									})
								}}>
								批量导出交强险
							</Button>
						</Permissions>
						<Permissions permissionID="amc_assetCenter_carMessage_insurance_commercial">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '114',
										queryDesc:
											'批量导出商业险,resourceId:114',
										queryParam: searchData,
									})
								}}>
								批量导出商业险
							</Button>
						</Permissions>
						<Permissions permissionID="amc_assetCenter_carMessage_insurance_liability">
							<Button
								icon={<ArrowDownOutlined />}
								className={styles.import}
								ghost
								size="small"
								onClick={() => {
									downloadDocumentUrl({
										resourceId: '115',
										queryDesc:
											'批量导出承责险,resourceId:115',
										queryParam: searchData,
									})
								}}>
								批量导出承责险
							</Button>
						</Permissions>
					</Space>
				</div>
				<CustomTable
					params={params}
					columns={columns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<BatchUpload
				{...batchUploadData}
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				getListData={getData}
				fileNmae="excel"
				modular="material"
				type={1}
				saveType={2}
				columns={errorColumns}
			/>
			<ImageImport
				isModalOpen={isCarImgModalOpen}
				setIsModalOpen={carImgModalOpen}
				accept={['image/jpeg', 'image/png']}
				moreNum={50}
				fileNmae={fileName}
				importData={importImgData}
				uploadFileUrl={uploadFileUrl}
			/>
		</div>
	)
}
export default connect(({user}: any) => ({user}))(archives)
